package com.lc.rongzecaifu.activity;

import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

import com.lc.rongzecaifu.MyApplication;
import com.lc.rongzecaifu.adapter.MyViewPager01Adapter;
import com.lc.rongzecaifu.conn.JsonAccessToken;
import com.lc.rongzecaifu.conn.JsonInvestdetail;
import com.lc.rongzecaifu.progress.SaundProgressBar;
import com.lc.rongzecaifu.rongzecaifu.R;
import com.lc.rongzecaifu.toast.LovelyToast;
import com.lc.rongzecaifu.ui.RegistWebActivity;
import com.lc.rongzecaifu.view.WrapContentViewPager;
import com.zcx.helper.bound.BoundViewHelper;
import com.zcx.helper.http.AsyCallBack;

import java.util.ArrayList;
import java.util.List;

import cn.iwgang.countdownview.CountdownView;


public class InvestmentActivity extends BaseActivity implements View.OnClickListener {

    private CountdownView cvinvesttime;
    private TextView tvinvest09;
    private TextView tvinvest10;
    private TextView tvinvest11;
    private TextView tvinvest12;
    private TextView tvtitle;
    private ImageView ivback;
    private TextView tvname;
    private TextView tvsumMoney;
    private TextView tvrate;
    private TextView tvtime;

    private TextView tvprogress;

    private TextView tvinvest02;
    private TextView tvinvest03;
    private TextView tvinvest05;
    private TextView tvinvest06;
    private TextView tvinvest07;
    private TextView tvinvest08;

    private TextView tv_invest_01;

    private Button btinvestnow;
    private String borrow_status, webUrl1, webUrl2, id;
    private List<View> viewList = new ArrayList<View>();
    private WrapContentViewPager vp01;
    private MyViewPager01Adapter myViewPager01Adapter;
//    private int[] heightList = new int[4];

    View tab_1;
    View tab_2;
    View tab_3;
    View tab_4;
    private ScrollView scroll_huadonglayout;

    private String str;

    private SaundProgressBar regularprogressbar;
    public static String getProduct;
    private PopupWindow popWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_investment);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        initView();
   /*     webUrl1 = getIntent().getStringExtra("url");
        webUrl1 = getIntent().getStringExtra("url");*/
        tab_1.setVisibility(View.VISIBLE);
        tab_2.setVisibility(View.GONE);
        tab_3.setVisibility(View.GONE);
        tab_4.setVisibility(View.GONE);


        tvinvest12.setOnClickListener(this);
        tvinvest11.setOnClickListener(this);
        tvinvest10.setOnClickListener(this);
        tvinvest09.setOnClickListener(this);
        btinvestnow.setOnClickListener(this);


        regularprogressbar.setMax(100);

        Drawable indicator = context.getResources().getDrawable(
                R.mipmap.jindu4);
        Rect bounds = new Rect(0, 0, indicator.getIntrinsicWidth(),
                indicator.getIntrinsicHeight());
        indicator.setBounds(bounds);

        regularprogressbar.setProgressIndicator(indicator);
        getAccessToken();
        getAccessToken1();

        getAccessToken2();


    }

    private void getAccessToken1() {
        Log.e("Invett", "getAccessToken1");
        new JsonAccessToken("index/invest_detail", new AsyCallBack<JsonAccessToken.Info>() {
            @Override
            public void onSuccess(String toast, int type, JsonAccessToken.Info info) throws Exception {
                Log.e("Invett", "onSuccess");
                if (info != null) {
                    if (!TextUtils.isEmpty(info.access_token)) {
                        //   http://vhost119.zihaistar.com/api/index/invest_detail?id=3&show_type=borrow_info&access_token=4d2685fae1729bfa0d9ac59c939996a0
                        webUrl1 = "http://www.rongzecf.com/api/index/invest_detail?id=" + getIntent().getStringExtra("id") + "&show_type=borrow_info" + "&access_token=" + info.access_token;
                        // webUrl1 = "https://www.haiying365.com/api/index/invest_detail?id=" + getIntent().getStringExtra("id") + "&show_type=borrow_info"+"&access_token="+info.access_token;
                        initData(info.access_token);
                        Log.d("onsucess:webUrl1:", webUrl1);
                    } else {
                        //   UtilToast.show(InvestmentActivity.this, "安全验证失败！");
                        LovelyToast.makeText(InvestmentActivity.this, "安全验证失败", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                    }
                }
            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                Log.e("Invett", "onSuccess");
                // UtilToast.show(InvestmentActivity.this, "安全验证失败！");
                LovelyToast.makeText(InvestmentActivity.this, "安全验证失败", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
            }

            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
                Log.e("Invett", "onStart");
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                Log.e("Invett", "onEnd");
            }
        }).execute(this, true);
    }

    private void getAccessToken2() {
        new JsonAccessToken("index/invest_detail", new AsyCallBack<JsonAccessToken.Info>() {
            @Override
            public void onSuccess(String toast, int type, JsonAccessToken.Info info) throws Exception {
                if (info != null) {
                    if (!TextUtils.isEmpty(info.access_token)) {
                        //   http://vhost119.zihaistar.com/api/index/invest_detail?id=3&show_type=borrow_info&access_token=4d2685fae1729bfa0d9ac59c939996a0
                        webUrl2 = "http://www.rongzecf.com/api/index/invest_detail?id=" + getIntent().getStringExtra("id") + "&show_type=borrow_risk" + "&access_token=" + info.access_token;

                        initData(info.access_token);
                        Log.d("webUrl2:" + webUrl2, "555555555555555555555555555555555555");
                    } else {
                        //  UtilToast.show(InvestmentActivity.this, "安全验证失败！");
                        LovelyToast.makeText(InvestmentActivity.this, "安全验证失败", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                    }
                }

            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                //  UtilToast.show(InvestmentActivity.this, "安全验证失败！");
                LovelyToast.makeText(InvestmentActivity.this, "安全验证失败", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
            }
        }).execute(this, true);
    }

    private void getAccessToken() {
        new JsonAccessToken("index/invest_detail", new AsyCallBack<JsonAccessToken.Info>() {
            @Override
            public void onSuccess(String toast, int type, JsonAccessToken.Info info) throws Exception {
                if (info != null) {
                    if (!TextUtils.isEmpty(info.access_token)) {
                        initData(info.access_token);
                    } else {
                        // UtilToast.show(InvestmentActivity.this, "安全验证失败！");
                        LovelyToast.makeText(InvestmentActivity.this, "安全验证失败", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                    }
                }
            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                // UtilToast.show(InvestmentActivity.this, "安全验证失败！");
                LovelyToast.makeText(InvestmentActivity.this, "安全验证失败", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
            }
        }).execute(this, true);

    }


    @Override
    protected void onResume() {
        super.onResume();


    }

    private void initData(String access_token) {
        new JsonInvestdetail(access_token, getIntent().getStringExtra("id"), "detail", new AsyCallBack<JsonInvestdetail.Info>() {
            @Override
            public void onSuccess(String toast, int type, JsonInvestdetail.Info info) throws Exception {
                if (info != null) {
                    tvname.setText(info.borrowinfo.borrow_name);
                    tvsumMoney.setText(info.borrowinfo.borrow_money);
                    tvrate.setText("年化收益  " + info.borrowinfo.borrow_interest_rate + "%");
                    tvtime.setText("项目期限  " + info.borrowinfo.borrow_duration + info.borrowinfo.borrow_duration_cn);
                    //tvtimeUnit.setText(info.borrowinfo.borrow_duration_cn);
                    tvprogress.setText(info.borrowinfo.progress + "%");

                    String string = info.borrowinfo.progress;
                    regularprogressbar.setmText(string);
                    int a;

//                    regularprogressbar.setProgress((int) Float.parseFloat(info.borrowinfo.progress));
                    String string1 = info.borrowinfo.progress;
                    Double db1 = Double.valueOf(string1);

                    int c = db1.intValue();
                    regularprogressbar.setProgress(c);
                    /*

                    if (c == 0) {
                        regularprogressbar.setProgress(1);
                    } else {
                        regularprogressbar.setProgress(c);
                    }
*/


                    //   Toast.makeText(context, c+"", Toast.LENGTH_SHORT).show();
                    //  tv_invest_01.setText("项目起期：" + info.borrowinfo.borrow_status_cn);

                    // tvinvest02.setText("项目起期：" + "审核通过后");
                    tvinvest02.setText("还款方式：" + info.borrowinfo.repayment_type_cn);

                    tvinvest03.setText("是否奖励：" + info.borrowinfo.reward_type_cn);

                    tvinvest05.setText(info.borrowinfo.need + "元");
                    tvinvest06.setText(info.borrowinfo.borrow_max + "元");
                    tvinvest07.setText(info.borrowinfo.borrow_min + "元");
                    tvinvest08.setText(info.borrowinfo.reward_type_cn);
                    //  btinvestnow.setText(info.borrowinfo.borrow_status_cn);
                    borrow_status = info.borrowinfo.borrow_status;
                    id = info.borrowinfo.id;

                    cvinvesttime.start(Integer.parseInt(info.borrowinfo.lefttime) * 1000);//ms
                    getProduct = info.borrowinfo.borrow_name;

                    tvname.setText(info.borrowinfo.borrow_name);
                    myViewPager01Adapter = new MyViewPager01Adapter(InvestmentActivity.this, viewList, webUrl1, webUrl2, info.investList, info.payingList);
                    scroll_huadonglayout.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View view, MotionEvent motionEvent) {
                            return false;
                        }
                    });
                    vp01.setAdapter(myViewPager01Adapter);
                    vp01.setCurrentItem(0);
                    tvinvest09.setSelected(true);
                } else {
                    // UtilToast.show(InvestmentActivity.this, JsonInvestdetail.TOAST);
                    LovelyToast.makeText(InvestmentActivity.this, JsonInvestdetail.TOAST, 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                }
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {

            }

        }).execute(this, false);
    }

    private void initView() {
        this.btinvestnow = (Button) findViewById(R.id.bt_invest_now);
        this.vp01 = (WrapContentViewPager) findViewById(R.id.vp_01);
        this.tvinvest12 = (TextView) findViewById(R.id.tv_invest_12);
        this.tvinvest11 = (TextView) findViewById(R.id.tv_invest_11);
        this.tvinvest10 = (TextView) findViewById(R.id.tv_invest_10);
        this.tvinvest09 = (TextView) findViewById(R.id.tv_invest_09);
        this.tvinvest08 = (TextView) findViewById(R.id.tv_invest_08);
        this.tvinvest07 = (TextView) findViewById(R.id.tv_invest_07);
        this.tvinvest06 = (TextView) findViewById(R.id.tv_invest_06);
        this.tvinvest05 = (TextView) findViewById(R.id.tv_invest_05);
        this.cvinvesttime = (CountdownView) findViewById(R.id.cv_invest_time);
        this.tvinvest03 = (TextView) findViewById(R.id.tv_invest_03);
        this.tvinvest02 = (TextView) findViewById(R.id.tv_invest_02);
        this.tv_invest_01 = (TextView) findViewById(R.id.tv_invest_01);
        this.tvprogress = (TextView) findViewById(R.id.tv_progress);
        // this.crpv = (ProgressBar) findViewById(R.id.crpv);
//        this.tvtimeUnit = (TextView) findViewById(R.id.tv_timeUnit);

        this.regularprogressbar = (SaundProgressBar) findViewById(R.id.regularprogressbar);
        this.tvtime = (TextView) findViewById(R.id.tv_time);
        this.tvrate = (TextView) findViewById(R.id.tv_rate);
        this.tvsumMoney = (TextView) findViewById(R.id.tv_sumMoney);
        this.tvname = (TextView) findViewById(R.id.tv_name);
        this.ivback = (ImageView) findViewById(R.id.iv_back);
        this.tvtitle = (TextView) findViewById(R.id.tv_title);
        tab_1 = findViewById(R.id.tab_1);
        tab_2 = findViewById(R.id.tab_2);
        tab_3 = findViewById(R.id.tab_3);
        tab_4 = findViewById(R.id.tab_4);


        viewList.add(BoundViewHelper.boundView(this, MyApplication.scaleScreenHelper.loadView((ViewGroup) LayoutInflater.from(this)
                .inflate(R.layout.vp_01_web_item_view, null))));
        viewList.add(BoundViewHelper.boundView(this, MyApplication.scaleScreenHelper.loadView((ViewGroup) LayoutInflater.from(this)
                .inflate(R.layout.vp_02_web_item_view, null))));
        viewList.add(BoundViewHelper.boundView(this, MyApplication.scaleScreenHelper.loadView((ViewGroup) LayoutInflater.from(this)
                .inflate(R.layout.vp_03_list_item_view, null))));
        viewList.add(BoundViewHelper.boundView(this, MyApplication.scaleScreenHelper.loadView((ViewGroup) LayoutInflater.from(this)
                .inflate(R.layout.vp_04_list_item_view, null))));

        scroll_huadonglayout = (ScrollView) findViewById(R.id.scroll_huadonglayout);
        vp01.setOffscreenPageLimit(5);

        for (int i = 0; i < viewList.size(); i++) {

            vp01.setObjectForPosition(viewList.get(i), i);

        }

        vp01.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                vp01.resetHeight(position);
                switch (position) {
                    case 0:
                        initTab();
                        tvinvest09.setSelected(true);
                        tab_1.setVisibility(View.VISIBLE);
                        tab_2.setVisibility(View.GONE);
                        tab_3.setVisibility(View.GONE);
                        tab_4.setVisibility(View.GONE);

                        break;

                    case 1:
                        initTab();
                        tvinvest10.setSelected(true);
                        tab_1.setVisibility(View.GONE);
                        tab_2.setVisibility(View.VISIBLE);
                        tab_3.setVisibility(View.GONE);
                        tab_4.setVisibility(View.GONE);
                        break;
                    case 2:
                        initTab();
                        tvinvest11.setSelected(true);
                        tab_1.setVisibility(View.GONE);
                        tab_2.setVisibility(View.GONE);
                        tab_3.setVisibility(View.VISIBLE);
                        tab_4.setVisibility(View.GONE);
                        break;
                    case 3:
                        initTab();
                        tvinvest12.setSelected(true);
                        tab_1.setVisibility(View.GONE);
                        tab_2.setVisibility(View.GONE);
                        tab_3.setVisibility(View.GONE);
                        tab_4.setVisibility(View.VISIBLE);
                        break;
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        vp01.resetHeight(0);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cvinvesttime.stop();
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_invest_09:
                vp01.setCurrentItem(0);
                tab_1.setVisibility(View.VISIBLE);
                tab_2.setVisibility(View.GONE);

                tab_3.setVisibility(View.GONE);

                tab_4.setVisibility(View.GONE);


                break;
            case R.id.tv_invest_10:
                vp01.setCurrentItem(1);
                tab_1.setVisibility(View.GONE);
                tab_2.setVisibility(View.VISIBLE);
                tab_3.setVisibility(View.GONE);
                tab_4.setVisibility(View.GONE);
                break;
            case R.id.tv_invest_11:
                vp01.setCurrentItem(2);
                tab_1.setVisibility(View.GONE);
                tab_2.setVisibility(View.GONE);

                tab_3.setVisibility(View.VISIBLE);

                tab_4.setVisibility(View.GONE);


                break;
            case R.id.tv_invest_12:
                vp01.setCurrentItem(3);
                tab_1.setVisibility(View.GONE);
                tab_2.setVisibility(View.GONE);

                tab_3.setVisibility(View.GONE);

                tab_4.setVisibility(View.VISIBLE);


                break;
            case R.id.bt_invest_now:
                if (TextUtils.isEmpty(MyApplication.myPreferences.readUid())) {
                    //  ToastUtils.show(this, "请登录后再操作！");
                    LovelyToast.makeText(InvestmentActivity.this, "请登录后再操作！", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (MyApplication.myPreferences.readStatus().equals("9")) {
                  /* LovelyToast.makeText(InvestmentActivity.this, "请开户之后再操作！", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);*/
                    showPopupWindow(btinvestnow);
                   /* Intent intent = new Intent();
                    intent.putExtra("id", id);
                    intent.putExtra("mode", true);
                    intent.putExtra("product", getProduct);
                    intent.setClass(this, PayActivity.class);
                    startActivity(intent);*/
                } else if (!TextUtils.isEmpty(borrow_status) && borrow_status.equals("2")) {
                    Intent intent = new Intent();
                    intent.putExtra("id", id);
                    intent.putExtra("mode", true);
                    intent.putExtra("product", getProduct);
                    intent.setClass(this, PayActivity.class);
                    startActivity(intent);
                } else {
                    LovelyToast.makeText(InvestmentActivity.this, "该项目不能投资！", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
              /*  Intent intent = new Intent();
                    intent.putExtra("id", id);
                    intent.putExtra("mode", true);
                    intent.putExtra("product", getProduct);
                    intent.setClass(this, PayActivity.class);
                    startActivity(intent);*/
                }
                break;
        }
    }

    private void initTab() {
        tvinvest12.setSelected(false);
        tvinvest11.setSelected(false);
        tvinvest10.setSelected(false);
        tvinvest09.setSelected(false);
    }
/*
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        resetViewPagerHeight(position);
        switch (position) {
            case 0:
                initTab();
                tvinvest09.setSelected(true);
                tab_1.setVisibility(View.VISIBLE);
                tab_2.setVisibility(View.GONE);

                tab_3.setVisibility(View.GONE);

                tab_4.setVisibility(View.GONE);
                break;
            case 1:
                initTab();
                tvinvest10.setSelected(true);
                tab_1.setVisibility(View.GONE);
                tab_2.setVisibility(View.VISIBLE);

                tab_3.setVisibility(View.GONE);

                tab_4.setVisibility(View.GONE);
                break;
            case 2:
                initTab();
                tvinvest11.setSelected(true);
                tab_1.setVisibility(View.GONE);
                tab_2.setVisibility(View.GONE);

                tab_3.setVisibility(View.VISIBLE);

                tab_4.setVisibility(View.GONE);
                break;
            case 3:
                initTab();
                tvinvest12.setSelected(true);
                tab_1.setVisibility(View.GONE);
                tab_2.setVisibility(View.GONE);

                tab_3.setVisibility(View.GONE);

                tab_4.setVisibility(View.VISIBLE);
                break;
        }


    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }*/

   /* public void resetViewPagerHeight(int position) {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) vp01
                .getLayoutParams();

        vp01.setLayoutParams(params);
        measureViewPagerHeight(position);

    }

    public void measureViewPagerHeight(int position) {
        View child = vp01.getChildAt(position);

    }*/


    private void showPopupWindow(View parent) {
        if (popWindow == null) {
            View view = BoundViewHelper.boundView(this, MyApplication.scaleScreenHelper.loadView((ViewGroup) LayoutInflater.from(this)
                    .inflate(R.layout.dialog_kaihu, null)));
            //LayoutParams相当于一个Layout的信息包，它封装了Layout的位置、高、宽等信息。
            popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            initPop(view);
        }
        //设置动画效果
        popWindow.setAnimationStyle(android.R.style.Animation_Dialog);
        //获取popwindow焦点
        popWindow.setFocusable(true);
        //设置popwindow如果点击外面区域，便关闭。
        popWindow.setOutsideTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        //实现软键盘不自动弹出,ADJUST_RESIZE属性表示Activity的主窗口总是会被调整大小，从而保证软键盘显示空间。
        popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置popwindow显示位置
        popWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }


    public void initPop(View view) {
        TextView tv01 = (TextView) view.findViewById(R.id.dl_tv_01);//拍照
        TextView tv02 = (TextView) view.findViewById(R.id.dl_tv_02);//相册


        final LinearLayout linear_dialog3 = (LinearLayout) view.findViewById(R.id.linear_dialog3);

        tv01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {

                popWindow.dismiss();
                popWindow = null;

            }
        });
        tv02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {

                Intent intent = new Intent();
                intent.putExtra("url", MyApplication.myPreferences.readRegistUrl());
                intent.setClass(InvestmentActivity.this, RegistWebActivity.class);
                startActivity(intent);
                popWindow.dismiss();
            }
        });
    }


}
